const Service = require("egg").Service;
const path = require("path");
const fs = require("fs");
const mkdirp = require("mkdirp");
const moment = require("moment");
const uuid = require("uuid");
const awaitStreamReady = require("await-stream-ready").write;
const sendToWormhole = require("stream-wormhole");
const { EVENT } = require("../extend/local");

function getDate() {
  var nowDate = new Date();
  var year = nowDate.getFullYear();
  var month =
    nowDate.getMonth() + 1 < 10
      ? "0" + (nowDate.getMonth() + 1)
      : nowDate.getMonth() + 1;
  var day =
    nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
  var dateStr = `${year}-${month}-${day}`;
  return dateStr;
}

/**
 * 判读路径是否存在,如不存在创建文件夹
 * @param pathStr 参数要用path.join()拼接,项目下的相对路径
 * @return projectPath 返回绝对路径,可要可不要
 */
function mkdirPath(pathStr) {
  var projectPath = path.join(process.cwd());
  var tempDirArray = pathStr.split("\\");

  for (var i = 0; i < tempDirArray.length; i++) {
    projectPath = projectPath + "/" + tempDirArray[i];
    if (fs.existsSync(projectPath)) {
      var tempstats = fs.statSync(projectPath);
      if (!tempstats.isDirectory()) {
        fs.unlinkSync(projectPath);
        fs.mkdirSync(projectPath);
      }
    } else {
      fs.mkdirSync(projectPath);
    }
  }
  return projectPath;
}

//保存头像到本地
class sUploadAvatar extends Service {
  async uploadFiles() {
    const { ctx } = this;
    const basePath = path.join("app/public/upload", getDate());
    // console.log("=======================");
    const file = ctx.request.files[0];
    // console.log("file: ", file);
    // console.log("basePath: ", basePath);
    // console.log("=======================");
    mkdirPath(basePath); // 生成本地对应文件夹
    const filename = getDate() + "/" + uuid.v1() + path.extname(file.filename).toLocaleLowerCase();
    const localFilePath = path.join(__dirname, "../public/upload", filename);
    const writeStream = fs.createWriteStream(localFilePath);
    let url = "";
    try {
      const readStream = fs.createReadStream(file.filepath); 
      // 将读取流管道到写入流，将文件保存到本地  
      await new Promise((resolve, reject) => {  
        readStream.pipe(writeStream);  
        readStream.on('error', reject);  
        writeStream.on('finish', resolve);  
      });  
      // 暂停流，防止内存泄漏
      // await awaitStreamReady(file.pipe(writeStream));
      url = EVENT.SERVER_ADDRESS + "/public/upload/" + filename;
    } catch (err) {
      console.log('err: ', err);
      await sendToWormhole(file);
      url = "";
    }
    return url;
  }
}
module.exports = sUploadAvatar;
